import logging

import client
import sqlite_db
from config import load_config, Settings
from create_bot import dp, bot
from middlewares.config import ConfigMiddleware
from middlewares.crypto import CryptoMiddleware
from middlewares.p2p import P2PMiddleware
from utils.broadcaster import broadcast
from utils.logger import configure_logging
import asyncio
import os
from aiocryptopay import AioCryptoPay, Networks
from aiogram import Bot
from aiogram.contrib.fsm_storage.memory import MemoryStorage
from aiogram.dispatcher import Dispatcher
from pyqiwip2p import QiwiP2P


logger = logging.getLogger(__name__)


def register_middlewares(config: Settings, p2p: QiwiP2P, crypto: AioCryptoPay):
    dp.setup_middleware(ConfigMiddleware(config))
    dp.setup_middleware(P2PMiddleware(p2p))
    dp.setup_middleware(CryptoMiddleware(crypto))


async def main():
    config = load_config()
    configure_logging()
    sqlite_db.sql_start()

    logger.error("Starting bot")

    p2p = QiwiP2P(auth_key=config.payment.qiwi_token)
    crypto = AioCryptoPay(token=config.payment.crypto_token, network=Networks.MAIN_NET)

    bot["config"] = config
    bot["p2p"] = p2p
    bot["crypto"] = crypto

    register_middlewares(config, p2p, crypto)
    import handlers  # НЕ УБИРАТЬ

    client.register_handlers_client(dp)

    # await broadcast (bot, config.tg_bot.admin_ids, "Бот запущен!")

    try:
        await dp.start_polling()
    finally:
        await dp.storage.close()
        await dp.storage.wait_closed()
        await bot.session.close()


def cli():
    """Wrapper for command line, app's entry point"""
    try:
        asyncio.run(main())
    except (KeyboardInterrupt, SystemExit):
        logger.error("Bot stopped!")


if __name__ == "__main__":
    cli()
